package com.hong.springcloud.test;

import com.hong.springcloud.entity.Product;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.HystrixCommandProperties;

/**
 * @Description:
 * @Author wanghong
 * @Date 2020/12/29 14:15
 * @Version V1.0
 **/
public class GetProductInfoCommand extends HystrixCommand<Product> {

    private Long productId;

    private static final HystrixCommandKey KEY = HystrixCommandKey.Factory.asKey("GetProductInfoCommand");

    public GetProductInfoCommand(Long productId){
        super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("ProductInfoService"))
        .andCommandKey(KEY)
        .andCommandPropertiesDefaults(HystrixCommandProperties.Setter()
        .withCircuitBreakerEnabled(true)
        .withCircuitBreakerRequestVolumeThreshold(20)
        .withCircuitBreakerErrorThresholdPercentage(40)
        .withCircuitBreakerSleepWindowInMilliseconds(3000)));

        this.productId = productId;
    }

    @Override
    protected Product run() throws Exception {
        System.out.println("调用接口查询商品数据,productId=" + productId);
        if (productId == -1){
            throw new Exception();
        }

        // 模拟微服务调用
        Thread.sleep(200);
        Product p = new Product();
        p.setId(productId);
        return p;
    }

    @Override
    protected Product getFallback() {
        Product p = new Product();
        p.setName("降级商品");
        return p;
    }
}
